<?
/**
 * Hi, I'm a Bootstrap File. All requests should go through me. I then 
 * dispatch Requests via Spaph_Controller to a Controller.method().
 * The dispatch starts with $spaph->run() below.
 *
 * I anticipate the following layout:
 *
 *    ./
 *    ./index.php
 *    ./config.php
 *    ./app/
 *      ./app/lib/
 *        ./app/lib/Spaph/
 *      ./app/plugins/
 *      ./app/views/
 *      ./app/controllers/
 *    ./static/error/
 *      ./static/error/404.html
 *      ./static/error/500.html
 *    ./static/css/
 *    ./static/js/
 *
 * Besides index and config, all other php files should
 * reside in the app directory.
 */

/*** Change the following two constants as needed ***/

define('CONFIG', 'config.php'); // set what config file to load,
                                // make sure there is a 
                                // [Load] section=Production

define('AUTOLOAD', 'app/lib');  // set the root directory for __autoload


/*** Hands off the rest of this Bootstrap file ***/

// Autoload
function __autoload($class) {
    $class = str_replace('_', '/', $class);
    $file  = AUTOLOAD.'/'.$class.'.php';

    if(!file_exists($file)) {
        error_log('Cannot load class: '.$file);
        die('Cannot load class: '.$class);
    }

    require($file);
}

// Get spaph object
$spaph = Spaph_Controller::getInstance();

// Get configuration
$load = new Spaph_Config(CONFIG,'Load');
$conf = new Spaph_Config(CONFIG,$load->section);

// Save conf
$spaph->config($conf);

// Set up base directory
$spaph->setControllerDir($conf->controllerDir);

// Set default action
$spaph->setAction($conf->default_action);

// Register plugins
$spaph->regPlugin($conf->plugins->toArray());

// Run this jalopy
try {
    $spaph->run();
}
catch(Spaph_Not_Found_Exception $e) {
    header('HTTP/1.0 404 Not Found');
    printFile('static/error/404.html');
}
catch(Exception $e) {
    foreach(array_reverse(explode("\n",$e->getTraceAsString())) as $t) { error_log($t); }
    error_log($e->getMessage().' in '.$e->getFile().' on line '.$e->getLine());
    header('HTTP/1.0 500 Server Error');
    printFile('static/error/500.html');
}

/**
 * A little function just to print a file to the screen.
 */
function printFile($file) {
    if(is_readable($file)) {
        $fh = fopen($file, 'r'); 
        while($data = fread($fh, 1024)) {
            print $data;
        }
        fclose($fh); 
    }
    else {
        die("The file (".basename($file).") is missing or unreadable.");
    }
}

